package com.bio.filter;

import com.bio.jpa.entities.User;
import com.bio.jsf.UserController;
import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionFilter implements Filter {

    FilterConfig fc;
    UserController uc;

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        fc = filterConfig;

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession(true);
        String pageRequested = req.getRequestURL().toString();

        if (!pageRequested.contains("javax.faces.resource")) {
            if (session.getAttribute("user") == null && !pageRequested.endsWith("login.bio") && !pageRequested.endsWith("SignUp.bio")) {
                //  System.out.println("Checking " + pageRequested);
                //   System.out.println("Sending to login page");
                resp.sendRedirect("/BioDesk/login.jsf?faces-redirect=true");
            } else {
                resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
                resp.setHeader("Pragma", "no-cache"); // HTTP 1.0.
                resp.setDateHeader("Expires", 0); // Proxies.


            }
        }
        chain.doFilter(request, response);

    }
}